package LinkedList;

/**
 * User:浪尘
 * Date:2022-09-24
 * Time:23:26
 */

/**
 * 链表的回文结构
 */
public class PalindromeList {
    class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
    public boolean chkPalindrome(ListNode A) {
        if (A == null) {//没有节点
            return false;
        }
        if (A.next == null) { //只有一个节点 一定是回文结构
            return true;
        }
        //找到中点
        ListNode fast = A;
        ListNode slow = A;
        ListNode cur = A;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        //翻转
        cur = slow.next;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curNext;
        }

        //比较
        while (A != slow) {
            if (A.val != slow.val) {//有一个不相等说明不是回文结构
                return false;
            }
            if (A.next == slow) {
                /*偶数情况下 A.next等于slow说明二者都遍历完成了,即将相遇,
                那么证明这个结构已经是回文结构了
                如果不加判断那么A继续next,slow继续next会往后走，就会判断错误！*/
                return true;
            }
            A = A.next;
            slow = slow.next;
        }
        return true;
    }

    public static void main(String[] args) {

    }
}
